import store from '@/store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Message } from 'ant-design-vue'
import notification from 'ant-design-vue/es/notification'
import axios from 'axios'
import qs from 'qs'
import storage from 'store'
import { VueAxios } from './axios'

// 创建 axios 实例
const request = axios.create({
    // API 请求的默认前缀
    baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 60000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
    if (error.response) {
        const data = error.response.data
        const token = storage.get(ACCESS_TOKEN)
        if (error.response.status === 401 || error.response.status === 403) {
            notification.error({
                message: '错误',
                description: data.message || 'token 过期或鉴权失败'
            })
            if (token) {
                store.dispatch('Logout').then(() => {
                    setTimeout(() => {
                        window.location.reload()
                    }, 1500)
                })
            }
        }
    }
    return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
    const token = storage.get(ACCESS_TOKEN)
    config.params = config.params || {}
    if (config.method.toLowerCase() === 'post' || config.method.toLowerCase() === 'delete') {
        if (config.method.toLowerCase() === 'post') {
            config.data = qs.stringify(config.data || {})
        }
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    } else {
        config.params.time = Date.now()
        config.headers['Content-Type'] = 'application/json; charset=utf-8'
    }
    config.headers['Authorization'] = `MtMnmDxncIGQ ${token}`

    return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
    const { data } = response
    console.log(data)
    if (data.code === 401) {
        Message.error(data.message)
        store.dispatch('Logout').then(() => {
            window.location.reload()
        })
    } else if (data.code !== 0) {
        Message.error(data.message)
        // eslint-disable-next-line new-cap
        return new Promise.reject(new Error(data.message))
    }
    return response.data
}, errorHandler)

const installer = {
    vm: {},
    install(Vue) {
        Vue.use(VueAxios, request)
    }
}

export default request

export {
    installer as VueAxios,
    request as axios
}
